<script setup lang="ts">
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  ElSelect,
  ElOption,
  TableColumnCtx,
  ElMessageBox,
  ElMessage,
  ElLoading
} from 'element-plus'
import 'element-plus/es/components/icon/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/tag/style/css'
import 'element-plus/es/components/menu/style/css'
import 'element-plus/es/components/menu-item/style/css'
import { PropType, reactive, ref, watch, h, computed, inject } from 'vue'
import { useTableDialogStore } from '@/store/modules/purchaseTableDialog'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { entryApi } from '@/api/purchase/index'
import { useI18n } from '@/hooks/web/useI18n'

const { formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

type tableDataType = {
  id: number
  cname: string
  code: string
  style_code: string
  unit: string
  num: number
  unit_price: number
  unit_sum: number
  notes: string
  entered_num: number
  entry_num: number
  warehouse: number | null
}

type stablSelectType = {
  value: number
  label: string
  chidren: stablSelectType[]
  disabled: boolean
}

interface SummaryMethodProps<T = tableDataType> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

interface TableService {
  getTableDet: () => any
}

const props = defineProps({
  tableDialogStoreID: {
    type: String,
    default: ''
  },
  tableDialogCurdSchema: {
    type: Array as PropType<CrudSchema[]>, // 明确类型为 CrudSchema[]
    default: () => [] // 设置默认值为一个空数组
  },
  modelValue: {
    type: Array as PropType<tableDataType[]>,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: () => false
  },
  warehouseList: {
    type: Array as PropType<stablSelectType[]>,
    default: () => []
  },
  futures: {
    type: Number,
    default: () => null
  }
})
console.log(props.warehouseList, 99)

const disablePastDates = (time) => {
  return time.getTime() < Date.now()
}

const emit = defineEmits(['update:modelValue'])

const { t } = useI18n()

const tableDialogStore = useTableDialogStore(props.tableDialogStoreID)

const tableData = ref<tableDataType[]>([])
const rowClassName = ({ row }) => (row.editing ? 'editing-row' : '')
const editCell = (row) => {
  row.editing = true
}

const filteredTableData = computed(() => {
  // 过滤 tableData
  return tableData.value.filter((row) => row.entered_num !== row.num)
})

const { getTableDet }: TableService = inject('getTableDet') as TableService

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.pid = tableDialogStore.selectedItems.map((item) => item.id).join(',')
    return formData
  }
}

const formRef = ref<any[]>([])

const setFormRef = (e) => {
  formRef.value.push(e)
}
const rules = ref({
  arrival_batch: [
    {
      required: true,
      trigger: ['blur'],
      validator: (rule: Record<string, any>, value: string, callback: Function) => {
        if (!value) {
          callback(new Error(t('purchase.batchValMsg')))
        } else {
          if (/^[A-Za-z0-9-_]{6,}$/.test(value)) {
            callback()
          } else {
            callback(new Error(t('purchase.batchValidation')))
          }
        }
      }
    }
  ]
})
const entryRow = async (row, index) => {
  if (row.warehouse && row.warehouse.length == 0) {
    ElMessage.error('请选择仓库')
    return
  }
  if (row.entry_num == 0) {
    ElMessage.error('入库数量不能为0')
    return
  }
  if (row.arrival_batch == '' || !row.arrival_batch) {
    ElMessage.error('期货商品批次不能为空')
    return
  }
  if ((row.delivery_date == '' || !row.delivery_date) && props.futures != 0) {
    ElMessage.error('到货日期不能为空')
    return
  }
  await formRef.value[index].validate((valid) => {
    if (valid) {
      ElMessageBox.confirm('确认入库商品? ', '入库商品', {
        confirmButtonText: t('confirmMessage.ok'),
        cancelButtonText: t('confirmMessage.cancel'),
        type: 'warning'
      }).then(async () => {
        let loadingInstance = {} as Record<string, any>
        try {
          loadingInstance = ElLoading.service({
            text: '正在入库，请稍候',
            background: 'rgba(0, 0, 0, 0.7)',
            fullscreen: true,
            lock: true
          })
          await entryApi({
            id: row.detail_id,
            entry_num: row.entry_num,
            warehouse: row.warehouse,
            futures: props.futures,
            arrival_batch: row.arrival_batch,
            delivery_date: row.delivery_date
          })
          await nextTick(() => {
            loadingInstance.close()
          })
          getTableDet()
          ElMessage.success('入库成功')
        } catch (e) {
          await nextTick(() => {
            loadingInstance.close()
          })
        }
      })
    }
  })
}

defineExpose({
  submit
})

const unitSums = reactive({})

const getSummaries = (param: SummaryMethodProps) => {
  const needHandleColumns = ['num', 'unit_price', 'unit_sum', 'entered_num', 'entry_num']
  // const needShowMoney = ['unit_price', 'unit_sum']
  const needShowMoney: string[] = []
  const { columns, data } = param
  const sums: string[] = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index.toString()] = h('div', { style: { textDecoration: 'underline' } }, ['Total Cost'])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (
      !values.every((value) => Number.isNaN(value)) &&
      needHandleColumns.includes(column.property)
    ) {
      sums[index] = `${needShowMoney.includes(column.property) ? '¥' : ''} ${values.reduce(
        (prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        },
        0
      )}`
    } else {
      sums[index] = 'N/A'
    }
  })

  return sums
}

watch(
  tableData,
  (newTableData) => {
    // 清空 unitSums
    Object.keys(unitSums).forEach((key) => delete unitSums[key])

    // 更新 unitSums
    newTableData.forEach((row, index) => {
      unitSums[index] = row.num * row.unit_price
      row.unit_sum = row.num * row.unit_price
    })
    // 更新表单数据
    emit('update:modelValue', newTableData)
  },
  { deep: true }
)

watch(
  () => props.modelValue,
  (val: any) => {
    tableData.value = val
  },
  {
    deep: true,
    immediate: true
  }
)
</script>

<template>
  <div>
    <el-table
      :data="filteredTableData"
      border
      show-summary
      :summary-method="getSummaries"
      style="width: 100%; margin-top: 10px"
      :row-class-name="rowClassName"
      @cell-click="editCell"
    >
      <el-table-column prop="cname" label="产品名称">
        <template #default="{ row }">
          <span>{{ row.cname }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="code" label="产品编号">
        <template #default="{ row }">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="style_code" label="规格">
        <template #default="{ row }">
          <span>{{ row.style_code }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="采购单位">
        <template #default="{ row }">
          <span>{{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="num" label="采购数量">
        <template #default="{ row }">
          <ElInputNumber disabled v-model="row.num" :min="1" type="number" />
        </template>
      </el-table-column>
      <el-table-column prop="entered_num" label="已入库数量">
        <template #default="{ row }">
          <ElInputNumber disabled v-model="row.entered_num" :min="0" type="number" />
        </template>
      </el-table-column>
      <el-table-column prop="entry_num" label="入库数量">
        <template #default="{ row }">
          <ElInputNumber
            v-model="row.entry_num"
            :min="0"
            :max="row.num - row.entered_num"
            type="number"
          />
        </template>
      </el-table-column>
      <el-table-column prop="warehouse" label="入库仓库">
        <template #default="{ row }">
          <!--          <ElSelect-->
          <!--            v-model="row.warehouse"-->
          <!--            placeholder="请选择仓库"-->
          <!--            size="small"-->
          <!--            :multiple="props.futures == 2"-->
          <!--            filterable-->
          <!--          >-->
          <!--            <ElOption-->
          <!--              v-for="item in props.warehouseList"-->
          <!--              :key="item.value"-->
          <!--              :label="item.label"-->
          <!--              :value="item.value"-->
          <!--            />-->
          <!--          </ElSelect>-->

          <el-tree-select
            v-model="row.warehouse"
            size="small"
            placeholder="请选择仓库"
            :data="props.warehouseList"
            filterable
            :multiple="props.futures == 2"
            check-strictly
            :render-after-expand="false"
            style="width: 240px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="arrival_batch" label="物流批次">
        <template #default="{ row }">
          <el-form
            :model="row"
            :ref="setFormRef"
            :rules="rules"
            :hide-required-asterisk="true"
            class="py-4"
          >
            <el-form-item label="" prop="arrival_batch">
              <el-input v-model="row.arrival_batch" placeholder="请输入最少6位批次码" />
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column v-if="props.futures != 0" prop="delivery_date" label="到货日期">
        <template #default="{ row }">
          <el-date-picker
            value-format="YYYY-MM-DD HH:mm:ss"
            :disabled-date="disablePastDates"
            v-model="row.delivery_date"
          />
        </template>
      </el-table-column>
      <el-table-column prop="unit_price" label="采购单价">
        <template #default="{ row }">
          <el-input disabled v-model="row.unit_price" />
        </template>
      </el-table-column>
      <el-table-column prop="unit_sum" label="单价小计">
        <template #default="{ row }">
          <el-input disabled v-model="row.unit_sum" />
        </template>
      </el-table-column>
      <!--      <el-table-column prop="notes" label="备注">-->
      <!--        <template #default="{ row }">-->
      <!--          <el-input disabled v-model="row.notes" />-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column fixed="right" label="操作" width="100">
        <template #default="scope">
          <ElButton
            class="input-button"
            size="small"
            type="primary"
            plain
            link
            @click.prevent="entryRow(scope.row, scope.$index)"
          >
            入库
          </ElButton>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.editing-row {
  background-color: #f5f7fa;
}
</style>
